import { t } from 'i18next'
import React, { useEffect, useRef, useState } from 'react'
import type { Dayjs } from 'dayjs'
import { percentOfDay, TIME } from '../translate'
import { IMeeting } from '../interface'
import { StyledColumn } from '../style'
import MeetingCard from './MeetingCard'
import dayjs from '@/plugins/dayjs'
import Alert from '@/components/Alert'
import ReactDOM from 'react-dom'
import { fetchStatus } from '@/api/global'
import { useGlobalStore } from '@/store/global'
import { fetchMeetingTimeExpired } from '@/api/myMeeting'

export interface ColumnBackgroundProps {
	day: string
	cellDivide?: number
	currentTime: Dayjs
	meetingList: IMeeting[]
}
interface IAddItemData {
	top: number
	left: number
	width: number
	height: number
	startTime: string
	endTime: string
}
/*
currentTime  当前时间
*/
const ColumnBackground = ({ day, cellDivide = 4, currentTime, meetingList }: ColumnBackgroundProps) => {
	const columnRef = useRef<HTMLDivElement>(null)
	const [width, setWidth] = useState<number>(0)
	const [isShowAddItem, setIsShowAddItem] = useState(false)
	const user = useGlobalStore((state) => state.user)
	const [addItemData, setAddItemData] = useState<IAddItemData>({
		top: 0,
		left: 0,
		width: 100,
		height: 25,
		startTime: '',
		endTime: '',
	})
	const isMoving = useRef(false)
	useEffect(() => {
		setWidth(Math.floor(columnRef.current?.offsetWidth || 0))
		const handler = () => {
			setWidth(Math.floor(columnRef.current?.offsetWidth || 0))
		}
		window.addEventListener('resize', handler)
		return () => {
			window.removeEventListener('resize', handler)
		}
	}, [])
	const handleMouseDown = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
		//销毁卡片弹窗
		let container = document.querySelector('.card-modal')
		container && ReactDOM.unmountComponentAtNode(container)
		//拉拽创会
		if (e.button === 2) return //禁止右键
		const calendarDom = document.querySelector('.calendar-body')
		const startScrollTop = calendarDom?.scrollTop ?? 0 //记录初始滚动位置
		const orgDom = e.target as any
		if (orgDom.className !== 'dotted-slot') return
		isMoving.current = true
		setIsShowAddItem(true)
		const startY = e.clientY
		let curItemData = {
			top: orgDom.offsetTop,
			left: orgDom.offsetLeft,
			width: orgDom.offsetWidth,
			height: 100,
			startTime: orgDom.dataset.top,
			endTime: dayjs(orgDom.dataset.top, 'HH:mm').add(1, 'hour').format('HH:mm'),
		}
		setAddItemData(curItemData)
		const handleMouseMove = (e: MouseEvent) => {
			if (!isMoving.current) return
			let offsetY = e.clientY - startY
			let curScrollTop = calendarDom?.scrollTop ?? 0 //记录初始滚动位置
			let offsetScroll = curScrollTop - startScrollTop
			let moveY = offsetY + offsetScroll
			let gridCount = Math.ceil(Math.abs(moveY) / 25)
			let height = gridCount * 25
			if (moveY > 0) {
				if (orgDom.offsetTop + height > 2400) return
				let endTime = dayjs(orgDom.dataset.bottom, 'HH:mm')
					.add((gridCount - 1) * 15, 'minute')
					.format('HH:mm')
				curItemData = {
					width: orgDom.offsetWidth,
					left: orgDom.offsetLeft,
					height,
					top: orgDom.offsetTop,
					startTime: orgDom.dataset.top,
					endTime: endTime === '00:00' ? '24:00' : endTime,
				}
			} else {
				if (orgDom.offsetTop - height + 15 < 0) return
				curItemData = {
					width: orgDom.offsetWidth,
					left: orgDom.offsetLeft,
					height,
					top: orgDom.offsetTop - height,
					startTime: dayjs(orgDom.dataset.top, 'HH:mm')
						.subtract(gridCount * 15, 'minute')
						.format('HH:mm'),
					endTime: orgDom.dataset.top,
				}
			}
			setAddItemData(curItemData)
		}
		const handleMouseUp = (e: MouseEvent) => {
			if (!isMoving.current) return
			isMoving.current = false
			setIsShowAddItem(false)
			document.removeEventListener('mousemove', handleMouseMove)
			document.removeEventListener('mouseup', handleMouseUp)

			//服务器时间可能会比电脑时间慢，导致后台校验通过，所以前台再和电脑时间校验一遍
			let time = dayjs(day + ' ' + curItemData.startTime + ':00').tz()
			let nowTime = dayjs()
			if (!user?.enable_meeting) {
				return
			}
			if (time.isBefore(nowTime)) {
				Alert(t('请在当前时间后创建会议'))
				return
			}
			fetchMeetingTimeExpired({ start_time: curItemData.startTime, day }).then((res) => {
				if (res.success) {
					// let searchMeetingRoom = {
					// 	startTime: curItemData.startTime,
					// 	endTime: curItemData.endTime,
					// 	duration: dayjs(day + '' + curItemData.endTime).diff(
					// 		dayjs(day + '' + curItemData.startTime),
					// 		'minute'
					// 	),
					// 	deviceIds: '',
					// 	personNumLowerLimit: '',
					// 	personNumUpperLimit: '',
					// 	regionId: '',
					// 	regionName: '',
					// 	meetingRoomId: '',
					// 	day: day,
					// 	meetingMoid: '',
					// }
					fetchStatus(() => {
						window.location.href =
							'./create.html?startTime=' +
							curItemData.startTime +
							'&day=' +
							day +
							'&endTime=' +
							curItemData.endTime +
							// `&meetingRoomId=""` +
							// `&searchMeetingRoom=` +
							// encodeURIComponent(JSON.stringify(searchMeetingRoom)) +
							'&source=searchRoom'
					})
				} else {
					Alert(res.description ?? t('创建失败'))
				}
			})
		}
		document.addEventListener('mousemove', handleMouseMove)
		document.addEventListener('mouseup', handleMouseUp)
	}
	return (
		<StyledColumn
			className={`list-column ${currentTime.isSame(day, 'date') ? 'curDay' : ''} ${
				isMoving.current ? 'moving' : ''
			}`}
			background={currentTime.isSame(day, 'date') ? '#ffffd6' : ''}
			ref={columnRef}
			onMouseDown={handleMouseDown}
		>
			{TIME.map((t, index) => {
				return (
					<div className="cell" key={t} draggable={false}>
						{Array.from({ length: cellDivide }).map((x, i) => {
							let topTime = dayjs(t, 'HH:mm')
								.minute(i * 15)
								.format('HH:mm')
							let bottomTime = dayjs(t, 'HH:mm')
								.minute((i + 1) * 15)
								.format('HH:mm')
							return (
								<div className="dotted-slot" key={i} data-top={topTime} data-bottom={bottomTime}></div>
							)
						})}
					</div>
				)
			})}
			{currentTime.isSame(day, 'date') && (
				<div className="current-time-line" style={{ top: percentOfDay(currentTime) }}></div>
			)}
			{meetingList.map((m, index) => (
				<MeetingCard
					key={m.meeting.meeting_moid + index}
					meeting={m}
					columnWidth={width}
					currentTime={currentTime}
				/>
			))}
			{isShowAddItem && (
				<div
					className="add-item"
					style={{
						top: `${addItemData.top}px`,
						left: `${addItemData.left}px`,
						width: `${addItemData.width}px`,
						height: `${addItemData.height}px`,
					}}
					draggable={false}
				>
					<div className="name">{t('{{name}}的会议', { name: user?.name })}</div>
					<div className="day">{dayjs(day).format(t('YYYY年MM月DD日'))}</div>
					<div className="add-start-time">
						{day} {addItemData.startTime}
					</div>
					<div className="add-end-time">
						{day} {addItemData.endTime}
					</div>
				</div>
			)}
		</StyledColumn>
	)
}
export default ColumnBackground
